# models.py
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericRelation
from mptt.models import MPTTModel, TreeForeignKey
from ctbloge import settings
from ctbloge.apps.cms.models import Article, Like


class Comment(MPTTModel):
    article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments', verbose_name='文章')
    content = models.TextField(verbose_name='评论内容')
    author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comments', on_delete=models.CASCADE,
                               verbose_name='评论者')
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children',
                            verbose_name='父评论')
    parent_content = models.TextField(null=True, blank=True, verbose_name='被回复的评论内容')
    is_approved = models.BooleanField(default=False, verbose_name='是否审核通过')
    created_date = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    likes = GenericRelation(Like)
    likes_count = models.PositiveIntegerField(default=0, verbose_name='点赞数')

    class MPTTMeta:
        order_insertion_by = ['created_date']

    class Meta:
        verbose_name = '评论列表'
        verbose_name_plural = verbose_name
        ordering = ['-created_date']

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        # 更新文章的评论计数
        self.article.comments_count = self.article.comments.count()
        self.article.save()


class Report(models.Model):  # 举报模型
    comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    reason = models.TextField()
    created_date = models.DateTimeField(auto_now_add=True)


class CommentLike(models.Model):  # 评论点赞模型
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    comment = models.ForeignKey(Comment, on_delete=models.CASCADE)


class Message(models.Model):
    """支持多种状态的私信系统"""
    SEND_STATUS = (
        (0, '未读'),
        (1, '已读'),
        (2, '撤回')
    )

    sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='sent_messages', on_delete=models.CASCADE,
                               verbose_name='发送者')
    receiver = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='received_messages', on_delete=models.CASCADE,
                                 verbose_name='接收者', default=1)
    content = models.TextField(max_length=2000, verbose_name='内容')
    status = models.SmallIntegerField(choices=SEND_STATUS, default=0, verbose_name='状态')
    is_sender_deleted = models.BooleanField(default=False, verbose_name='发送者是否删除')
    is_receiver_deleted = models.BooleanField(default=False, verbose_name='接收者是否删除')
    created_date = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        ordering = ['-created_date']
        indexes = [
            models.Index(fields=['receiver', 'status']),
            models.Index(fields=['created_date'])
        ]


class Notification(models.Model):
    """支持多类型聚合的通知系统"""
    NOTIFICATION_TYPES = (
        ('comment', '评论'),
        ('reply', '回复'),
        ('like', '点赞'),
        ('follow', '关注'),
        ('collect', '收藏'),
        ('message', '留言'),
        ('system', '系统通知'),
        ('mention', '@提及')
    )
    STATUS_CHOICES = (
        ('unread', '未读'),
        ('read', '已读')
    )
    title = models.CharField(max_length=50, verbose_name='通知标题', null=True, blank=True, default='你有新的消息')

    receiver = models.ForeignKey(settings.AUTH_USER_MODEL,
                                 related_name='notifications',
                                 on_delete=models.CASCADE,
                                 verbose_name='接收者')
    sender = models.ForeignKey(settings.AUTH_USER_MODEL,
                              related_name='notified_users',
                              blank=True,
                              null=True,
                              on_delete=models.SET_NULL,
                              verbose_name='发送者')
    verb = models.CharField(max_length=20, choices=NOTIFICATION_TYPES, verbose_name='通知类型')
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='unread')
    is_sender_deleted = models.BooleanField(default=False, verbose_name='发送者是否删除')
    is_receiver_deleted = models.BooleanField(default=False, verbose_name='接收者是否删除')
    system_level = models.CharField(max_length=20, blank=True, null=True,
                                    choices=[('urgent', '紧急'), ('normal', '普通')],
                                    verbose_name='系统通知级别')
    expire_time = models.DateTimeField(null=True, blank=True,
                                       verbose_name='过期时间（适用于系统通知）')
    is_broadcast = models.BooleanField(default=False,
                                       verbose_name='是否广播通知')
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name='通知时间')
    content = models.TextField(blank=True, null=True, verbose_name='通知内容')

    class Meta:
        ordering = ['-timestamp']
        indexes = [
            models.Index(fields=['sender']),
            models.Index(fields=['receiver']),
            models.Index(fields=['verb']),
            models.Index(fields=['status']),
        ]
